package es.unileon.is.finalproyect.temporizer;

import javax.swing.AbstractButton;

public class Temporizer extends Thread implements TimeSource {

	private long _nextTimestamp;
	private int _seconds;
	private AbstractButton _endButton;
	private volatile boolean _done = false;
	
	private TimeEventHandler _handler;
	
	
	public Temporizer(int seconds, AbstractButton endButton) {
		_seconds = seconds++;
		_endButton = endButton;
		_handler = new TimeEventHandler();
	}
	@Override
	public void addTimeListener(TimeListener tl) {
		_handler.addTimeListener(tl);
	}
	
	@Override
	public void removeTimeListener(TimeListener tl) {
		_handler.removeTimeListener(tl);
	}
	
	@Override
	public void nextSecond() {
		_seconds--;
		_handler.fireNewTime(this, _seconds);
	}
	
	public synchronized void setDone(){
		_done = true;
	}
	
	public void run(){
		_nextTimestamp = System.currentTimeMillis()+1000;
		nextSecond();
		while(!_done){
			try {
				Thread.currentThread().sleep(_nextTimestamp - System.currentTimeMillis());
				_nextTimestamp = System.currentTimeMillis()+1000;
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			if(_seconds <= 0){
				_endButton.doClick();
				_done = true;
			} else {
				nextSecond();
			}
		}
	}
	
}
